#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QFile>
#include <QThread>
extern "C" {

    #include <libavcodec/avcodec.h>
    #include <libavformat/avformat.h>
    #include <libavutil/avutil.h>

}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
     const char * format = "avfoundation";
     AVInputFormat* inputFormat = av_find_input_format(format);

     if(inputFormat == nullptr) {

         qDebug() << "format " << format << "error";
         return;
     }

     AVFormatContext *fmtContext = nullptr;
     const char* url = ":0";
     AVDictionary* dict = nullptr;
     int result = avformat_open_input(&fmtContext,url,inputFormat, &dict);

     if(result != 0) {

         char buf[1024];
         av_strerror(result,buf,sizeof(buf));
         qDebug() << buf << "\n";
         avformat_close_input(&fmtContext);
         return;
     }

     qDebug() << "1111";


     AVPacket packet;
     int count = 500;


//     av_free_packet(&packet);

     const char* audio_file_path = "/Users/tgy/Documents/ffmpeg/audio/out.pcm";
     QFile file(audio_file_path);


     if(!file.open(QFile::WriteOnly)) {

         qDebug() << "audio_file_path:" << audio_file_path << " write error";
     }


     while(count > 0) {

         int read_result = av_read_frame(fmtContext,&packet);
         if(read_result == 0) {

             qDebug() << packet.size << " =====";
             count--;
             file.write((char *)packet.data,packet.size);
         }else if(read_result != -35){

             char buf[1024];
             av_strerror(read_result,buf,sizeof(buf));
             qDebug() << buf << "\n";
             break;
         }

        qDebug() << read_result ;

     }

     file.close();

     avformat_close_input(&fmtContext);
}
